package edu.mse.camel.client.core.idcache;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;

import edu.mse.camel.client.core.plugin.Activator;
import edu.mse.camel.client.log.Debug;

public class TargetModelIDCache {
	
	private Map<ModelID, EObject> idCache;
	protected EObject modelRoot;
	private ModelID newID;
	
	public TargetModelIDCache(EObject modelRoot) {
		idCache = new HashMap<ModelID, EObject>();
		this.modelRoot = modelRoot;
		newID = null;
	}

	public void generateCache() {
		TreeIterator<EObject> iterator = 
			EcoreUtil.getAllContents(Collections.singleton(modelRoot));
		int i = 0;
		while (iterator.hasNext()) {
			EObject eObject = iterator.next();
			Debug.log_info(Activator.PLUGIN_ID, "Generating id for: " + EcoreUtil.getIdentification(eObject));
			ModelID newID = new ModelID(i++);
			idCache.put(newID, eObject);
		}
		newID = new ModelID(i);
	}
	
	public EObject getElement(ModelID modelID) {
		return idCache.get(modelID);
	}
	
	public void addElementRecursive(EObject eObject, ModelID modelID) {
		TreeIterator<EObject> iterator = 
			EcoreUtil.getAllContents(Collections.singleton(eObject));
		int i = modelID.getID();
		while (iterator.hasNext()) {
			EObject childEObject = iterator.next();
			Debug.log_info(Activator.PLUGIN_ID, "Generating id for: " + EcoreUtil.getIdentification(childEObject));
			ModelID newID = new ModelID(i++);
			idCache.put(newID, childEObject);
		}		
	}
	
}
